package com.ja.controller;

import com.alibaba.fastjson.JSON;
import com.ja.config.PayConfig;
import com.ja.domain.AdminUser;
import com.ja.domain.Jine;
import com.ja.domain.User;
import com.ja.sevice.JineService;
import com.ja.sevice.LiushuiService;
import com.ja.util.DateUtil;
import com.ja.util.MapCacheUtil;
import com.ja.util.Md5;
import com.ja.util.PayCrypt3Des;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.Map;

/**
 * Created by Administrator on 2019-05-09.
 */
@Controller
@RequestMapping("/pay")
public class NotifyController {
    @Autowired
    private LiushuiService liushuiService;

    /**
     * 方法名：notify
     * 描述：     通知页面
     * 参数：    @return
     *
     * @return: String
     */
    @RequestMapping("/notify")
    @ResponseBody
    public String notifyAction(HttpServletRequest req, HttpServletResponse response, HttpSession session,
                               @RequestParam("MerchantID") String merchantID,
                               @RequestParam("Signature") String signature,
                               @RequestParam("RspCode") String rspCode,
                               @RequestParam("RspMsg") String rspMsg,
                               @RequestParam("PayResponse") String payResponse
    ) {
        // todo

        HttpServletRequest httpServletRequest = req;
        System.out.println(httpServletRequest);



        //支付通回调参数
      //  String rspCode = "";//响应码
      //  String rspMsg = "";//响应信息
        // String merchantID = merchantID;//商户号
      //  String signature = "";//验签码
      //  String payResponse = "";//响应信息 Json 格式的字符串整体报文都会以 3DES 加密处理

        //rspCode=="0000" 标识正确返回，具体根据Status判断订单状态
        if (rspCode.equals("0000")) {
            try {

                String resultJsonStr = PayCrypt3Des.decrypt3DES(URLDecoder.decode(payResponse, "utf-8")
                        , PayConfig.DES3_KEY, PayConfig.DES3_IV);

                String server_signature = Md5.encryptMd5(PayConfig.MERCHANTID + resultJsonStr + PayConfig.MD5_KEY);


                System.out.println("response:" + resultJsonStr);
                //2.验签
                if (server_signature.equals(signature)) {

					/*
                    PayResponse      //响应信息 Json 格式的字符串整体报文都会以 3DES 加密处理
			            MerBillNo 订单号
			            Amount 订单金额
			            PayType 支付类型码
			            UserId
			            ReqDate
			            TradeNo 支付系统流水号
			            PayBillTime 订单时间
			            SignType 验签类型
			            Attach 附加参数回传
			            Currency 币种
			            Status (成功:success,失败:failure,处理中:processing)
	              */
                    Map<String, Object> resultMap = (Map<String, Object>) JSON.parse(resultJsonStr);

                    //3。Stauts=="success" 时为支付成功,其他参数说请参照文档
                    if ("success".equals(resultMap.get("Status").toString())) {
                        //商户端正确接收通知后需应答 "pay_result_ok" 表示该订单已完成支付平台方将该订单标记为完成，否则支付平台方会重复请求 重复次数达到15次 无论成功将不再进行通知。
                        //由于通知会重复请求请商户方请做好逻辑防重处理。
                        //支付成功接收后商户端业务处理 TODO......

                        //4.验证订单金额

                        //5.修改订单状态，请务必做好重复回调处理
                        String key = (String) session.getAttribute("key");
                        if (key != null && key.equals(resultMap.get("MerBillNo").toString())) {
//                            System.out.println("pay_result_ok______1");
                            return "pay_result_ok";
                        }
                        session.setAttribute("key", resultMap.get("MerBillNo").toString());



                        Jine jine = new Jine();// 存入充值信息
                        jine.setName("name" + resultMap.get("UserId").toString());
                        jine.setOrdernum(resultMap.get("MerBillNo").toString());
                        if ("ALIQR".equals(resultMap.get("PayType").toString())) {
                            jine.setZhifupt("支付宝扫码");
                        } else if ("WXQR".equals(resultMap.get("PayType").toString())) {
                            jine.setZhifupt("微信扫码");
                        } else {
                            jine.setZhifupt("银联支付");
                        }

                        jine.setFukuanje(Double.parseDouble(resultMap.get("Amount").toString()));
                        jine.setCkname("-");
                        jine.setZhifuzh("-");
                        jine.setHydengji("在线");
                        jine.setSqtime(resultMap.get("PayBillTime").toString());//订单时间
                        jine.setCltime(DateUtil.getCurrTime());
                        jine.setType("在线充值");
                        jine.setState("支付成功");
                        jine.setCaozuo("已操作");
                        jine.setCzname("系统自动");
                        jine.setStatus(1);
                        jine.setBeizhu("在线充值:" + resultMap.get("TradeNo").toString());
                       // jine.setUserid(Integer.parseInt(resultMap.get("UserId").toString()));
                        String userId = MapCacheUtil.getString(resultMap.get("MerBillNo").toString());
                        if(userId == null){
                            // 之前正确处理,直接返回
                            return "pay_result_ok";
                        }

                        jine.setUserid(Integer.parseInt(userId));

                        MapCacheUtil.remove(resultMap.get("MerBillNo").toString()); //去掉key

                        //6.返回 pay_result_ok 支付系统将标记该订单已回调成功

                        User user = new User();
                        user.setId(Integer.parseInt(userId));

                        AdminUser adminUser = new AdminUser();
                        adminUser.setName("在线充值");
                        liushuiService.changeRecord(user,adminUser,resultMap.get("MerBillNo").toString(),Double.parseDouble(resultMap.get("Amount").toString()),jine,jine.getZhifupt(),1);

//                        System.out.println("pay_result_ok");
                        session.removeAttribute("key");
//                        System.out.println("pay_result_ok______2");
                        return "pay_result_ok";
                    } else {
                        System.out.println(resultMap.get("Status").toString());
                    }

                } else {

                    System.out.println("支付通知商户端验签失败!");
                }
            } catch (Exception ex) {

                System.out.print("error:" + ex.getMessage() + ex.getStackTrace());
            }

        } else {
            System.out.println("支付平台响应:" + rspMsg);
        }


        return "pay_result_error";
    }


    /**
     * 方法名：paySuccess
     * 描述：     充值成功页面
     * 参数：    @return
     *
     * @return: String
     */
    @RequestMapping("/paySuccess")
    public String paySuccess() {
        return "pc/personal/paysuccess";
    }

}
